import 'package:flutter/material.dart';
import 'network/api_client.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Secure Communication Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: LoginScreen(),
    );
  }
}

class LoginScreen extends StatefulWidget {
  @override
  _LoginScreenState createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  final _formKey = GlobalKey<FormState>();
  final _usernameController = TextEditingController();
  final _passwordController = TextEditingController();
  final _apiClient = ApiClient();
  bool _isLoading = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Secure Login'),
      ),
      body: Padding(
        padding: EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              TextFormField(
                controller: _usernameController,
                decoration: InputDecoration(
                  labelText: 'Username (try: admin)',
                  border: OutlineInputBorder(),
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return 'Please enter username';
                  }
                  return null;
                },
              ),
              SizedBox(height: 16),
              TextFormField(
                controller: _passwordController,
                decoration: InputDecoration(
                  labelText: 'Password (try: password)',
                  border: OutlineInputBorder(),
                ),
                obscureText: true,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return 'Please enter password';
                  }
                  return null;
                },
              ),
              SizedBox(height: 24),
              ElevatedButton(
                onPressed: _isLoading ? null : _login,
                child: _isLoading 
                    ? CircularProgressIndicator() 
                    : Text('Login (Encrypted)'),
              ),
              SizedBox(height: 16),
              ElevatedButton(
                onPressed: _isLoading ? null : _testPing,
                child: Text('Test Ping (No Encryption)'),
              ),
            ],
          ),
        ),
      ),
    );
  }

  void _login() async {
    if (!_formKey.currentState!.validate()) {
      return;
    }

    setState(() {
      _isLoading = true;
    });

    try {
      final response = await _apiClient.login(
        _usernameController.text,
        _passwordController.text,
      );

      if (response['success'] == true) {
        _showMessage('Login successful!');
        Navigator.pushReplacement(
          context,
          MaterialPageRoute(builder: (context) => UserScreen()),
        );
      } else {
        _showError(response['message'] ?? 'Login failed');
      }
    } catch (e) {
      _showError('Login error: $e');
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  void _testPing() async {
    setState(() {
      _isLoading = true;
    });

    try {
      final response = await _apiClient.ping();
      _showMessage('Ping successful: ${response['message']}');
    } catch (e) {
      _showError('Ping error: $e');
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  void _showError(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(message), backgroundColor: Colors.red),
    );
  }

  void _showMessage(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(message), backgroundColor: Colors.green),
    );
  }
}

class UserScreen extends StatefulWidget {
  @override
  _UserScreenState createState() => _UserScreenState();
}

class _UserScreenState extends State<UserScreen> {
  final _apiClient = ApiClient();
  Map<String, dynamic>? _userInfo;
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    _loadUserInfo();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('User Info (Encrypted)'),
        actions: [
          IconButton(
            icon: Icon(Icons.refresh),
            onPressed: _loadUserInfo,
          ),
          IconButton(
            icon: Icon(Icons.logout),
            onPressed: () => Navigator.pushReplacement(
              context,
              MaterialPageRoute(builder: (context) => LoginScreen()),
            ),
          ),
        ],
      ),
      body: _isLoading
          ? Center(child: CircularProgressIndicator())
          : _userInfo == null
              ? Center(child: Text('No user info available'))
              : Padding(
                  padding: EdgeInsets.all(16.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Card(
                        child: Padding(
                          padding: EdgeInsets.all(16.0),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text('User Information', 
                                style: Theme.of(context).textTheme.headlineSmall),
                              SizedBox(height: 16),
                              if (_userInfo!['data'] != null) ...[
                                Text('ID: ${_userInfo!['data']['id']}'),
                                SizedBox(height: 8),
                                Text('Username: ${_userInfo!['data']['username']}'),
                                SizedBox(height: 8),
                                Text('Email: ${_userInfo!['data']['email']}'),
                                SizedBox(height: 8),
                                Text('Phone: ${_userInfo!['data']['phone']}'),
                              ],
                            ],
                          ),
                        ),
                      ),
                      SizedBox(height: 16),
                      ElevatedButton(
                        onPressed: _updateUserInfo,
                        child: Text('Update User Info (Encrypted)'),
                      ),
                      SizedBox(height: 8),
                      Text(
                        'Note: All communication on this page is encrypted using AES-256-CBC',
                        style: TextStyle(color: Colors.grey[600], fontSize: 12),
                      ),
                    ],
                  ),
                ),
    );
  }

  void _loadUserInfo() async {
    setState(() {
      _isLoading = true;
    });

    try {
      final response = await _apiClient.getUserInfo();
      setState(() {
        _userInfo = response;
      });
    } catch (e) {
      _showError('Failed to load user info: $e');
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  void _updateUserInfo() async {
    final updatedInfo = {
      'id': 1,
      'username': 'admin_updated',
      'email': 'admin_updated@example.com',
      'phone': '13900139000',
    };

    try {
      final response = await _apiClient.updateUserInfo(updatedInfo);
      if (response['success'] == true) {
        _showMessage('User info updated successfully');
        _loadUserInfo();
      } else {
        _showError(response['message'] ?? 'Update failed');
      }
    } catch (e) {
      _showError('Update error: $e');
    }
  }

  void _showError(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(message), backgroundColor: Colors.red),
    );
  }

  void _showMessage(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(message), backgroundColor: Colors.green),
    );
  }
}
